package io.coderyeah.system.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.coderyeah.basic.Result;
import io.coderyeah.system.domain.Role;
import io.coderyeah.system.dto.RoleDTO;
import io.coderyeah.system.service.RoleService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/role")
public class RoleController {
    @Autowired
    private RoleService roleService;

    @GetMapping
    public Result getAll() {
        return Result.success(roleService.list());
    }

    // 获取分页数据
    @ApiOperation("获取分页数据")
    @PostMapping("list")
    public Result list(@RequestBody RoleDTO roleDTO) {
        final Page<Role> rolePage = new Page<>(roleDTO.getCurrentPage(), roleDTO.getPageSize());
        final LambdaQueryWrapper<Role> wrapper = new LambdaQueryWrapper<>();
        if (StrUtil.isNotBlank(roleDTO.getKeyword())) {
            wrapper.like(Role::getName, roleDTO.getKeyword()).or().like(Role::getSn, roleDTO.getKeyword());
        }
        final Page<Role> page = roleService.page(rolePage, wrapper);
        return Result.success(page.getRecords(), page.getTotal());
    }

    // 添加修改操作
    @ApiOperation("添加修改操作")
    @PutMapping
    public Result AddOrModify(@RequestBody Role role) {
        return roleService.AddOrModify(role);
    }

    @ApiOperation("删除角色")
    @DeleteMapping("{id}")
    public Result deleteById(@PathVariable("id") Long id) {
        return roleService.deleteById(id);
    }

    @ApiOperation("批量删除")
    @PatchMapping
    public Result deleteByBatch(@RequestBody RoleDTO roleDTO) {
        final List<Long> ids = roleDTO.getIds();
        for (int i = 0; i < ids.size(); i++) {
            deleteById(ids.get(i));
        }
        return Result.success(null);
    }
}
